package com.prizedraw.prize_draw.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.prizedraw.prize_draw.common.lang.Result;
import com.prizedraw.prize_draw.entity.*;
import com.prizedraw.prize_draw.service.DepartmentRoleService;
import com.prizedraw.prize_draw.service.DepartmentService;
import com.prizedraw.prize_draw.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;



@RestController
@RequestMapping("/department")
public class DepartmentController extends BaseController {

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    DepartmentRoleService departmentRoleService;

    /**
     * 这个方法只用于级联选择器的数据渲染
     * @return
     */
    @GetMapping("/listAll")
    @PreAuthorize("hasAuthority('department:list')")
    public Result listAll(){
        List<Department> departments = departmentService.list();
          departments.forEach(d -> {
            d.setChildren(sysRoleService.listRolesByDepartmentId(d.getId()));
        });
        return Result.succ(departments);
    }


    /**
     * 列表
     * @param departmentName
     * @return
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('department:list')")
    public Result list(String departmentName){
        Page<Department> pageData = departmentService.page(getPage(),
                new QueryWrapper<Department>()
                .like(StrUtil.isNotBlank(departmentName),"name",departmentName));

        pageData.getRecords().forEach(d -> {
            d.setChildren(sysRoleService.listRolesByDepartmentId(d.getId()));
        });
        return Result.succ(pageData);
    }


    /**
     * 添加
     * @param department
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('department:save')")
    public Result save (@Validated @RequestBody Department department){
        int count = departmentService.count(new QueryWrapper<Department>()
                .eq("name", department.getName()));
        if (count > 0){
            return Result.fail("该部门岗位已存在");
        }
        departmentService.save(department);
        return Result.succ("");
    }


    /**
     * 添加
     * @param department
     * @return
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('department:update')")
    public Result update(@RequestBody Department department){
        boolean flag = departmentService.getById(department.getId()).getName().equals(department.getName());
        if (!flag){
            int count = departmentService.count(new QueryWrapper<Department>()
                    .eq("name", department.getName()));
            if (count > 0){
                return Result.fail("该部门岗位已存在");
            }
        }
        departmentService.updateById(department);
        return Result.succ("");
    }

    @Transactional
    @PreAuthorize("hasAuthority('department:delete')")
    @PostMapping("/delete")
    public Result delete(@RequestBody Integer[] ids){
        int count = 0;
        for (Integer id : ids) {
            count = departmentRoleService.count(new QueryWrapper<DepartmentRole>().eq("department_id", id));
            if (count > 0) {
                return Result.fail("请先删除部门所拥有的岗位");
            }
        }
        departmentService.removeByIds(Arrays.asList(ids));
        return Result.succ("");
    }



}
